package cn.tedu.eguser.controller;

import cn.tedu.eguser.base.response.JsonResult;
import cn.tedu.eguser.base.response.StatusCode;
import cn.tedu.eguser.mapper.UserMapper;
import cn.tedu.eguser.pojo.dto.UserAddParam;
import cn.tedu.eguser.pojo.dto.UserUpdateParam;
import cn.tedu.eguser.pojo.entity.User;
import cn.tedu.eguser.pojo.vo.UserListVO;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.添加用户功能
     */
    @PostMapping("add")
    public JsonResult addUser(@Validated @RequestBody UserAddParam userAddParam){
        System.out.println("userAddParam: " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        System.out.println("准备添加数据库: " + user);
        int i = userMapper.insertUser(user);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 2.用户列表功能
     */
    @GetMapping("list")
    public JsonResult listUser(){
        return JsonResult.ok(userMapper.selectUserList());
    }

    /**
     * 3.用户删除功能
     */
    @PostMapping("del")
    public JsonResult delUser(@Range(min = 1L, max = 100L, message = "用户编号必须在1-100之间") Long id){
        System.out.println("id = " + id);
        int i = userMapper.deleteUserById(id);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    /**
     * 4.用户修改功能
     */
    @PostMapping("update")
    public JsonResult updateUser(@RequestBody UserUpdateParam userUpdateParam){
        System.out.println("userUpdateParam: " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        System.out.println("准备修改数据库: " + user);
        int i = userMapper.updateUserById(user);
        if (i > 0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }
}










